<template>
  <div class="hiddenScroll">
    <LayoutContainer>
      <div class="pay">
        <el-scrollbar max-height="400px" style="width: 100%">
          <div class="goods-list">
            <GoodPage v-for="item in goodsInfo" :obj="item"></GoodPage>
          </div>
        </el-scrollbar>
        <div class="address-manage">
          <h2 class="title font-color">收货地址</h2>
          <AddressPage v-if="addressData.length > 0" v-for="item in addressData" :obj="item" @close="updateOldAddress"
            @change="changeAddress"></AddressPage>
          <el-empty v-else description="暂未添加过收获地址" />
          <el-button type="primary" @click="addNewAddress = true" v-if="addressData.length < 3">
            添加收获地址&nbsp;
            <el-icon>
              <Plus />
            </el-icon>
          </el-button>
        </div>
        <OrderDetails v-if="goodsInfo.length > 0" :obj="goodsInfo"></OrderDetails>
        <DeliveryAddress ref="deliveryAddress" v-if="addressChoose" :obj="addressChoose" @buy="buy"></DeliveryAddress>
      </div>
      <AddNewAddress v-if="addNewAddress" @close="closeAddressDialog"></AddNewAddress>
    </LayoutContainer>
  </div>
</template>

<script setup>
import { nextTick, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import GoodPage from './components/GoodPage.vue'
import AddressPage from './components/AddressPage.vue'
import OrderDetails from './components/OrderDetails.vue'
import DeliveryAddress from './components/DeliveryAddress.vue'
import AddNewAddress from './components/AddNewAddress.vue'
import LayoutContainer from '@/layout/LayoutContainer.vue'
import { addOrder, getAllAddress, getGoodsDetail } from '@/api/shop'
import { startLoading, stopLoading } from '@/utils/loading'
import { getBalanceIntegral, updateBalanceIntegral } from '@/api/user'

// 获取路由器实例
const router = useRouter()

const goodsInfo = ref([])

// 初始化数据
const init = async () => {
  const goods = JSON.parse(sessionStorage.getItem('chase'))
  if (!goods) {
    await router.replace('/shop')
    return
  }
  sessionStorage.removeItem('chase')
  goodsInfo.value = await Promise.all(
    goods.map(async (item) => {
      const { id } = item
      const { data } = (await getGoodsDetail(id)).data
      data.number = item.number
      return data
    }),
  )
}

// 保存数据
window.addEventListener('beforeunload', function (event) {
  sessionStorage.setItem('chase', JSON.stringify(goodsInfo.value))
})

// 添加地址弹窗
const addNewAddress = ref(false)

// 定义地址数据
const addressData = ref([])

// 选中地址
const addressChoose = ref('')

// 下单ref对象
const deliveryAddress = ref()

// 更改地址
const changeAddress = (newAddress) => {
  addressChoose.value = newAddress
  nextTick(() => {
    deliveryAddress.value.changeAddress(newAddress)
  })
}

// 获取所有地址
const getAddress = async () => {
  startLoading()
  addressData.value = (await getAllAddress()).data.data
  stopLoading()
  changeAddress(addressData.value[0]?.address)
}

// 关闭地址弹窗
const closeAddressDialog = async () => {
  addNewAddress.value = false
  await getAddress()
}

// 更新旧地址
const updateOldAddress = async (obj) => {
  await getAddress()
  const id = obj.id
  const addressItem = addressData.value.find((item) => {
    return item.id === id
  })
  obj.fn(addressItem)
}

// 下单
const buy = async () => {
  const price = goodsInfo.value.reduce((sum, cur) => sum + cur.number * cur.price, 0)
  const integral = goodsInfo.value.reduce((sum, cur) => sum + cur.number * cur.integral, 0)
  ElMessageBox.confirm(`确认支付${price}元和${integral}积分以购买商品？`, {
    confirmButtonText: '确定', // 修改确认按钮文本
    cancelButtonText: '取消', // 修改取消按钮文本
  }).then(async () => {
    const { data } = (await getBalanceIntegral()).data
    if (data.balance < price) {
      ElMessage({
        message: '账户余额不足',
        type: 'error',
      })
      return
    } else if (data.integral < integral) {
      ElMessage({
        message: '账户积分不足',
        type: 'error',
      })
      return
    }
    // 下单
    for (const item of goodsInfo.value) {
      const obj = {
        goodsId: item.id,
        name: item.name,
        number: item.number,
        totalPrice: item.price * item.number,
        totalIntegral: item.integral * item.number,
        address: addressChoose.value,
        description: item.description,
        image: item.images[0],
        identityName: item.identityName,
      }
      // 添加订单
      const res = (await addOrder(obj)).data
      if (!res.success) {
        continue
      }
    }
    // 扣除余额
    await updateBalanceIntegral({
      balance: +data.balance - price,
      integral: +data.integral - integral,
    })
    ElMessage.success('下单成功')
    await router.replace('/shop')
  })
}

onMounted(() => {
  init()
  getAddress()
})
</script>

<style scoped less="scss">
.pay {
  display: flex;
  flex-direction: column;
  justify-content: center;

  width: 90%;
  margin: 80px auto;
  transition: all 0.3s;
  box-shadow: 0px 1px 5px 0px rgba(0, 0, 0, 0.1);

  .goods-list {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-self: center;
    gap: 10px;

    margin: auto;
    width: 96%;
    padding: 10px;
  }

  .address-manage {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    width: 95%;
    min-height: 100px;
    margin: 20px auto;
    padding-bottom: 20px;
    box-shadow: 0px 1px 5px 0px rgba(0, 0, 0, 0.1);

    .title {
      width: 100%;
      padding: 10px 0 0 10px;
    }
  }
}
</style>
